//---------------------------------------------------------------------
//  This file is part of the Background Motion solution.
// 
//  Copyright (C) Mindscape (TM).  All rights reserved.
//  http://www.mindscape.co.nz
// 
//  THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY
//  KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
//  IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A
//  PARTICULAR PURPOSE.
//---------------------------------------------------------------------

using System;
using System.Collections;
using System.Collections.Generic;
using System.Web.UI.WebControls;

using Mindscape.BackgroundMotion.Model;

namespace Mindscape.BackgroundMotion.Website.Controls
{
  public class TagCloudData : IEnumerable
  {
    private readonly double _scaleFactor;

    #region TagCloudDataItem

    public class TagCloudDataItem
    {
      private readonly Tag _tag;
      private readonly TagCloudData _tagCloudData;

      public TagCloudDataItem(Tag tag, TagCloudData tagCloud)
      {
        _tag = tag;
        _tagCloudData = tagCloud;
      }

      public int Id
      {
        get { return _tag.Id; }
      }

      public string Style
      {
        get { return "margin: " + _tagCloudData.TagMargin + "px"; }
      }
      
      public string Value
      {
        get { return string.Format("{0}", _tag.Value); }
      }

      public FontUnit Size
      {
        get { return new FontUnit(Math.Min(Math.Round(
          ((double)_tag.Usages / (double)_tagCloudData.MaxUsages) 
          + _tagCloudData._scaleFactor, 1), _tagCloudData.MaxTagSize) + "em"); }
      }
    }

    #endregion

    private readonly IList<TagCloudDataItem> _tagCloudDataItems 
      = new List<TagCloudDataItem>();

    private int _maxUsages;

    private readonly int _tagMargin;
    private readonly double _maxTagSize;

    public TagCloudData(IList<Tag> tags)
      : this(tags, 1.4, 8, 2.4)
    {
    }

    public TagCloudData(IList<Tag> tags, double scaleFactor, int tagMargin, double maxTagSize)
    {
      _scaleFactor = scaleFactor;
      _tagMargin = tagMargin;
      _maxTagSize = maxTagSize;

      foreach (Tag tag in tags)
      {
        _tagCloudDataItems.Add(new TagCloudDataItem(tag, this));
        _maxUsages = Math.Max(tag.Usages, _maxUsages);
      }
    }

    public int MaxUsages
    {
      get { return _maxUsages; }
    }

    public double MaxTagSize
    {
      get { return _maxTagSize; }
    }

    public double ScaleFactor
    {
      get { return _scaleFactor; }
    }

    public int TagMargin
    {
      get { return _tagMargin; }
    }

    public IEnumerator GetEnumerator()
    {
      return _tagCloudDataItems.GetEnumerator();
    }
  }
}